package com.bank.frame;

import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;

import com.bank.dao.AccountDAO;
import com.bank.dao.RecordDAO;
import com.bank.utils.SystemConstants;

/**
 * 管理员进行账户操作
 */
public class AdminAccountTablePanel extends JInternalFrame {

	public AdminAccountTablePanel() {
		super("账户查询", true, true, true, true);
		this.setSize(SystemConstants.FRAME_WIDTH, SystemConstants.FRAME_HEIGHT);
		//创建表格，设置为不可更改
		JTable table = new JTable() {
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		// 进来的时候表格是空的，必须输入身份证号之后才能显示
		TableModel tableModel = new DefaultTableModel(new Object[][] {}, AccountDAO.columnNames);
		table.setModel(tableModel);

		// 隐藏列开始，隐藏密码
		TableColumnModel tcm = table.getColumnModel();//得到表格的数据
		TableColumn tc = tcm.getColumn(8);//得到第八列的数据
		//相关宽度全部设置为0
		tc.setMaxWidth(0);
		tc.setPreferredWidth(0);
		tc.setWidth(0);
		tc.setMinWidth(0);
		//表头对应的也应设置为0
		tcm = table.getTableHeader().getColumnModel();
		tc = tcm.getColumn(8);
		tc.setMaxWidth(0);
		tc.setPreferredWidth(0);
		tc.setWidth(0);
		tc.setMinWidth(0);
		// 隐藏列结束

		JPanel topPanel = new JPanel();
		JTextField nameField = new JTextField(20);
		topPanel.add(new JLabel("身份证号："));
		topPanel.add(nameField);
		JButton searchBtn = new JButton("查询");
		topPanel.add(searchBtn);
		JButton recordBtn = new JButton("交易记录");
		topPanel.add(recordBtn);
		JButton addBtn = new JButton("开户");
		topPanel.add(addBtn);
		JButton editBtn = new JButton("修改");
		topPanel.add(editBtn);
		JButton inBtn = new JButton("存款");
		topPanel.add(inBtn);
		JButton outBtn = new JButton("取款");
		topPanel.add(outBtn);
		JButton delBtn = new JButton("注销");
		topPanel.add(delBtn);
		JPanel panel = new JPanel(new BorderLayout());
		panel.setSize(SystemConstants.FRAME_WIDTH, SystemConstants.FRAME_HEIGHT);
		// 查询账号
		searchBtn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				refresh(table, nameField.getText());
			}
		});
		// 选中一条账户信息，点击交易记录，查看该卡所有交易记录
		recordBtn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				int rowNum = table.getSelectedRow();
				if (rowNum <= -1) {
					return;
				}
				com.bank.frame.AdminPanel.setContent(new com.bank.frame.RecordTablePanel(table.getValueAt(rowNum, 0).toString(),
						table.getValueAt(rowNum, 1).toString()));
			}
		});
		// 开户
		addBtn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				com.bank.frame.AdminPanel.setContent(new AccountEditPanel(null));//开户时传入参数为null
			}
		});
		// 修改
		editBtn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				int rowNum = table.getSelectedRow();
				if (rowNum <= -1) {
					return;
				}
				if (SystemConstants.ACCOUNT_STATUS_DISABLE.equals(table.getValueAt(rowNum, 7).toString())) {
					//判断这张卡是不是注销状态
					JOptionPane.showMessageDialog(editBtn.getParent(), "该账户已注销", "系统提示", JOptionPane.WARNING_MESSAGE);
					return;
				}
				com.bank.frame.AdminPanel.setContent(new AccountEditPanel(table.getValueAt(rowNum, 0)));//传入的参数是卡号
			}
		});
		// 存款
		inBtn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				int rowNum = table.getSelectedRow();
				if (rowNum <= -1) {
					return;
				}
				if (SystemConstants.ACCOUNT_STATUS_DISABLE.equals(table.getValueAt(rowNum, 7).toString())) {
					//判断是否注销
					JOptionPane.showMessageDialog(editBtn.getParent(), "该账户已注销", "系统提示", JOptionPane.WARNING_MESSAGE);
					return;
				}
				String card = table.getValueAt(rowNum, 0).toString();
				String input = JOptionPane.showInputDialog(inBtn.getParent(), "请输入存款金额", "系统提示",
						JOptionPane.WARNING_MESSAGE);
				if (input == null) {
					return;
				}
				double amount;//定义用来存储输入的存款金额
				try {
					amount = Double.parseDouble(input);
				} catch (Exception ex) {
					// 如果输入的是字符串会报异常
					ex.printStackTrace();
					JOptionPane.showMessageDialog(inBtn.getParent(), "金额无效", "系统提示", JOptionPane.WARNING_MESSAGE);
					return;
				}
				if (amount <= 0) {
					JOptionPane.showMessageDialog(inBtn.getParent(), "金额无效", "系统提示", JOptionPane.WARNING_MESSAGE);
					return;
				}

				Object[] account = AccountDAO.findByCard(card);
				// 验证二类卡限额  ||  二类卡限制每日 （存款 + 转入） 金额不大于 1w 元
				if (SystemConstants.ACCOUNT_TYPE_II.equals(account[6])) {
					double today = RecordDAO.getTodayAmount(account[0].toString(), "in");//  得到今天的转入金额
					if (today + amount > 10000) {
						JOptionPane.showMessageDialog(inBtn.getParent(), "Ⅱ类卡单日转入(含存款)限额1万,当前已交易" + today, "系统提示",
								JOptionPane.WARNING_MESSAGE);
						return;
					}
				}
				// 增加余额
				account[4] = (double) account[4] + amount;
				AccountDAO.update(card, account);

				// 记录交易记录："交易编号", "卡号", "交易时间", "交易类型", "交易金额", "余额",
				// "对方姓名", "对方账户", "交易备注"
				Object[] record = new Object[] { System.currentTimeMillis(), account[0],
						SystemConstants.DATE_FORMAT.format(new Date()), SystemConstants.TRADE_TYPE_SAVING, "+" + amount,
						account[4], "", "", "柜台存入" };// 存款，所以对方姓名和对方账户为null
				RecordDAO.add(record);
				refresh(table, nameField.getText());

			}
		});
		// 取款
		outBtn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				int rowNum = table.getSelectedRow();
				if (rowNum <= -1) {
					return;
				}
				if (SystemConstants.ACCOUNT_STATUS_DISABLE.equals(table.getValueAt(rowNum, 7).toString())) {
					//  判断是否注销
					JOptionPane.showMessageDialog(editBtn.getParent(), "该账户已注销", "系统提示", JOptionPane.WARNING_MESSAGE);
					return;
				}
				// 卡号
				String card = table.getValueAt(rowNum, 0).toString();
				// 取款需要密码
				String input = JOptionPane.showInputDialog(outBtn.getParent(), "请用户输入取款密码", "系统提示",
						JOptionPane.WARNING_MESSAGE);
				if (input == null) {
					return;
				}
				Object[] account = AccountDAO.findByCard(card);
				if (!input.equals(account[8])) {
					//  如果密码不正确报错
					JOptionPane.showMessageDialog(delBtn.getParent(), "密码错误", "系统提示", JOptionPane.WARNING_MESSAGE);
					return;
				}
				//  密码正确继续向下指向
				input = JOptionPane.showInputDialog(outBtn.getParent(), "请输入取款金额", "系统提示", JOptionPane.WARNING_MESSAGE);
				if (input == null) {
					return;
				}
				double amount;
				try {
					amount = Double.parseDouble(input);
				} catch (Exception ex) {
					ex.printStackTrace();
					JOptionPane.showMessageDialog(inBtn.getParent(), "金额无效", "系统提示", JOptionPane.WARNING_MESSAGE);
					return;
				}
				if (amount <= 0) {
					JOptionPane.showMessageDialog(outBtn.getParent(), "金额无效", "系统提示", JOptionPane.WARNING_MESSAGE);
					return;
				}
				if ((double) account[4] < amount) {
					JOptionPane.showMessageDialog(outBtn.getParent(), "余额不足", "系统提示", JOptionPane.WARNING_MESSAGE);
					return;
				}
				// 验证二类卡限额
				if (SystemConstants.ACCOUNT_TYPE_II.equals(account[6])) {
					double today = RecordDAO.getTodayAmount(account[0].toString(), "out");
					if (today - amount < -10000) {
						JOptionPane.showMessageDialog(inBtn.getParent(), "Ⅱ类卡单日转出(含取款)限额1万,当前已交易" + today, "系统提示",
								JOptionPane.WARNING_MESSAGE);
						return;
					}
				}
				// 减掉余额，并记录
				account[4] = (double) account[4] - amount;
				AccountDAO.update(card, account);
				Object[] record = new Object[] { System.currentTimeMillis(), account[0],
						SystemConstants.DATE_FORMAT.format(new Date()), SystemConstants.TRADE_TYPE_WITHDRAW,
						"-" + amount, account[4], "", "", "柜台取款" };
				RecordDAO.add(record);
				refresh(table, nameField.getText());
			}
		});
		// 注销
		delBtn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				int rowNum = table.getSelectedRow();
				if (rowNum <= -1) {
					return;
				}
				if (SystemConstants.ACCOUNT_STATUS_DISABLE.equals(table.getValueAt(rowNum, 7).toString())) {
					//  判断卡是否注销
					JOptionPane.showMessageDialog(editBtn.getParent(), "该账户已注销", "系统提示", JOptionPane.WARNING_MESSAGE);
					return;
				}
				String input = JOptionPane.showInputDialog(delBtn.getParent(), "请用户输入密码", "系统提示",
						JOptionPane.WARNING_MESSAGE);
				if (input == null) {
					return;
				}
				String card = table.getValueAt(rowNum, 0).toString();
				Object[] account = AccountDAO.findByCard(card);
				if (!input.equals(account[8])) {
					JOptionPane.showMessageDialog(delBtn.getParent(), "密码错误", "系统提示", JOptionPane.WARNING_MESSAGE);
					return;
				}
				account[7] = SystemConstants.ACCOUNT_STATUS_DISABLE;  // 更改账户状态
				// 注销时要把钱全取出来
				double amount = (double) account[4];
				account[4] = 0.0;
				AccountDAO.update(card, account);
				Object[] record = new Object[] { System.currentTimeMillis(), account[0],
						SystemConstants.DATE_FORMAT.format(new Date()), SystemConstants.TRADE_TYPE_WITHDRAW,
						"-" + amount, account[4], "", "", "注销-柜台取款" };
				RecordDAO.add(record);
				JOptionPane.showMessageDialog(delBtn.getParent(), "注销成功", "系统提示", JOptionPane.INFORMATION_MESSAGE);
				refresh(table, nameField.getText());
			}

		});
		// 把 表头 添加到容器顶部（使用普通的中间容器添加表格时，表头 和 内容 需要分开添加）
		panel.add(table.getTableHeader(), BorderLayout.NORTH);
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // 单选
		// 把 表格内容 添加到容器中心
		this.add(topPanel, BorderLayout.NORTH);
		panel.add(table, BorderLayout.CENTER);
		this.add(panel, BorderLayout.CENTER);
		// 显示内部窗口
		this.setVisible(true);
	}

	// 每次改变数据后，刷新表格内容
	public void refresh(JTable table, String text) {
		TableModel tableModel = new DefaultTableModel(AccountDAO.search(1, text), AccountDAO.columnNames);
		table.setModel(tableModel);
		// 隐藏列开始
		TableColumnModel tcm = table.getColumnModel();
		TableColumn tc = tcm.getColumn(8);
		tc.setMaxWidth(0);
		tc.setPreferredWidth(0);
		tc.setWidth(0);
		tc.setMinWidth(0);
		tcm = table.getTableHeader().getColumnModel();
		tc = tcm.getColumn(8);
		tc.setMaxWidth(0);
		tc.setPreferredWidth(0);
		tc.setWidth(0);
		tc.setMinWidth(0);
		// 隐藏列结束
	}
}
